<?php

namespace app\db\controller;

use app\db\model\DbUsercareAuth;
use fast\Tree;

class DbAuth extends Common
{
    protected $noNeedLogin = ['add', 'edit', 'del', 'index'];
    protected $noNeedRight = [];
    protected $model = null;
    protected $rulelist = [];

    public function _initialize()
    {
        parent::_initialize();
        //移除HTML标签
        $this->request->filter('trim,strip_tags,htmlspecialchars');
        $this->model = model('DbUsercareAuth');

        // 必须将结果集转换为数组
        $ruleList = \think\Db::name("db_usercare_auth")->order('weigh DESC,id ASC')->select();
        Tree::instance()->init($ruleList);
        $this->rulelist = $ruleList;
    }


    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $list   = $this->rulelist;
            $total  = count($this->rulelist);
            $result = array("total" => $total, "rows" => $list);
            $this->success(__('Operation completed'), $result);
        } else {
            $this->error(__('Operation failed'));
        }
    }

    /**
     * 添加规则
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                if (!$params['ismenu'] && !$params['pid']) {
                    $this->error(__('The non-menu rule must have parent'));
                }
                $result = $this->model->validate()->save($params);
                if ($result === false) {
                    $this->error($this->model->getError());
                }
                $this->success(__('Operation completed'));
            }
            $this->error(__('Invalid parameters'));
        } else {
            $this->error(__('No Post request'));
        }
    }

    /**
     * 编辑
     */
    public function edit()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $row    = $this->model->get(['id' => $params['id']]);
            if (!$row) {
                $this->error(__('No Results were found'));
            }
            if ($params) {
                if (!$params['ismenu'] && !$params['pid']) {
                    $this->error(__('The non-menu rule must have parent'));
                }
                if ($params['pid'] == $row['id']) {
                    $this->error(__('Can not change the parent to self'));
                }
                if ($params['pid'] != $row['pid']) {
                    $childrenIds = Tree::instance()->init(collection(DbUsercareAuth::select())->toArray())->getChildrenIds($row['id']);
                    if (in_array($params['pid'], $childrenIds)) {
                        $this->error(__('Can not change the parent to child'));
                    }
                }
                $result = $row->validate()->save($params);
                if ($result === false) {
                    $this->error($row->getError());
                }
                $this->success(__('Operation completed'));
            }
            $this->error(__('Invalid parameters'));
        } else {
            $this->error(__('No Post request'));
        }
    }

    /**
     * 删除
     */
    public function del()
    {
        if (!$this->request->isPost()) {
            $this->error(__("No Post request"));
        }
        $id = $this->request->post("id");
        if ($id) {
            $delIds = [];
            foreach (explode(',', $id) as $k => $v) {
                $delIds = array_merge($delIds, Tree::instance()->getChildrenIds($v, true));
            }
            $delIds = array_unique($delIds);
            $count  = $this->model->where('id', 'in', $delIds)->delete();
            if ($count) {
                $this->success(__('Operation completed'));
            }
        }
        $this->error('Invalid parameters');
    }

    /**
     * @Notes:getTreeList  获取当前医生的权限列表
     * @author:WuXiaoMing
     * Date:2021/8/21
     * Time:3:45 下午
     */
    public function getTreeList()
    {
        $relation_id = input('post.relation_id');
        if (!$relation_id) $this->error(__('Invalid parameters'));
        //获取当前医生的权限ID
        $relation_auth = model('DbUsercareRelation')->where('id', $relation_id)->value('relation_auth');
        $relation_arr  = explode(',', $relation_auth);
        //获取系统权限列表
        $ruleList = model('DbUsercareAuth')->get_auth('id,pid,name', 'weigh DESC');
        //调用tree,返回树结构
        $res  = Tree::instance()->init($ruleList)->getTreeArray(0);
        $data = [
            'list'    => $res,
            'checked' => $relation_arr,
        ];
        $this->success(__(''), $data);
    }


}
